package com.example.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.vo.Result;
import com.example.sys.entity.Role;

import com.example.sys.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuage
 * @since 2023-12-20
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @GetMapping("/list")
    public Result<Map<String,Object>> getRoleList(@RequestParam(value = "roleName",required = false) String roleName,
                                                  @RequestParam(value = "pageNo")Long pageNo,
                                                  @RequestParam(value = "pageSize")Long pageSize){
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasLength(roleName),"role_name",roleName);

        Page<Role> page = new Page<>(pageNo,pageSize);
        roleService.page(page,wrapper);

        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return Result.success(data);
    }

    @PostMapping("/addrole")
    public Result<?> addRole(@RequestBody Role role){
        roleService.addRole(role);
        return Result.success("新增角色成功");
    }

    @PutMapping("/updaterole")
    public Result<?>  updateRole(@RequestBody Role role){
        roleService.updateRole(role);
        return Result.success("修改角色成功");
    }

    @GetMapping("/getrole/{id}")
    public Result<Role> getRoleByID(@PathVariable Integer id){
        Role role = roleService.getRoleByID(id);
        return Result.success(role);
    }

    @DeleteMapping("/deleterole/{id}")
    public Result<Role> deletRoleByID(@PathVariable Integer id){
        roleService.deleterole(id);
        return Result.success("删除用户成功");
    }

    @GetMapping("/all")
    public Result<List<Role>> getAllRole(){
        List<Role> list = roleService.list();
        return Result.success(list);
    }
}
